import React, { Component } from 'react'
import PropTypes from 'prop-types'
import { Table } from 'antd'
import {
  Wrapper
} from './style'

class PageTable extends Component {
  constructor (props) {
    super(props)

    this.state = {
      tbody: [],
      page: 1,
      total: 0
    }

    this.pageChange = this.pageChange.bind(this)
    this.searchData = this.searchData.bind(this)
    this._getList = this._getList.bind(this)
  }

  componentDidMount () {
    this._getList()
  }

  render () {
    const { tbody, total, page } = this.state
    const { tableProps, pageProps } = this.props

    return (
      <Wrapper>
        <Table
          bordered
          size="small"
          {...tableProps}
          pagination={{
            size: 'small',
            showQuickJumper: true,
            ...pageProps,
            current: page ,
            total
          }}
          dataSource={tbody}
          onChange={this.pageChange}
        ></Table>
      </Wrapper>
    )
  }

  pageChange (page) {
    this.setState(() => ({
      page: page.current
    }), () => {
      this._getList()
    })
  }

  actionData () {
    this._getList()
  }

  searchData () {
    this.setState(() => ({
      page: 1
    }), () => {
      this._getList()
    })
  }

  _getList () {
    this.props.controllLoading(true)

    this.props.getList({
      page: this.state.page,
      searchValue: this.props.searchValue(),
      callback: res => {
        this.setState(() => ({
          tbody: res.data.rows,
          total: res.data.total
        }))
      },
      complete: res => {
        this.props.controllLoading(false)
      }
    })
  }
}

PageTable.propTypes = {
  tableProps: PropTypes.object,
  pageProps: PropTypes.object,
  searchValue: PropTypes.func,
  getList: PropTypes.func,
  controllLoading: PropTypes.func
}

PageTable.defaultProps = {
  tableProps: {},
  pageProps: {},
  searchValue: () => {},
  getList: () => {},
  controllLoading: () => {}
}

export default PageTable
